/*!
  \file utils.h
  \brief Implementation of miscellaneous functions used by the compression and
  decompression programs.
*/

#ifndef _UTILS_H_
#define _UTILS_H_

#include <stdio.h>
#include <sys/stat.h>

/**
  Opens a file with the provided filename and checks for errors.
  \param filename - Name of the file to be opened.
  \param mode - Must be "w" for writing mode or "r" for reading mode.
  \param fp - File pointer to the file. This will be NULL when the function 
  returns if there was an error while opening the file.
  \param must_exist - Either 1 or 0. Pass 1 if the file must exist; 0
  otherwise. Note that output files don't have to exist prior the running of
  the program, but input files do.
  \return -1 if an error occurred, 0 otherwise.
*/
int open_file(char *filename, char *mode, FILE **fp, int must_exist)
{
  struct stat file_stat;
  int status;
  
  printf("Opening %s...\n", filename);
  
  status = lstat(filename, &file_stat);
  if (must_exist && status == -1) {
    printf("File %s does not exist.\n", filename);
    return -1;
  }
  
  if (status == 0 && !S_ISREG(file_stat.st_mode)) {
    printf("File %s must be a regular file.\n", filename);
    return -1;
  }
  
  *fp = fopen(filename, mode);
  if (*fp == NULL) {
    printf("Unable to open file %s\n", filename);
    return -1;
  }
  rewind(*fp);

  printf("File %s opened successfully...\n", filename);
  return 0;
}

#endif

